<?php

App::uses('AppController', 'Controller');

/**
 * Transactions Controller
 *
 * @property Transaction $Transaction
 * @property PaginatorComponent $Paginator
 */
class TransactionsController extends AppController
{

    public $helpers = array('Form', 'Html');

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator');

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {

        $this->Transaction->recursive = 0;
        $this->paginate = array('conditions' => array('Wallet.user_id' => $this->Auth->user('id'), 'Wallet.default' => '1'), 'order' => array('Transaction.created' => 'DESC'));
        $wallets = $this->Transaction->Wallet->find('all', array('conditions' => array('Wallet.user_id' => $this->Auth->user('id')), 'recursive' => -1));
        $transactions = $this->Paginator->paginate();
        $dates = $this->viewdate();
        $category_spent = $this->getcatefirst();
        //debug($category_spent);die;
        $this->set(compact('transactions', 'wallets', 'dates', 'category_spent'));
        //debug($transactions);
        //$dates = $this->viewdate();
    }

    /*
     * get transactions by date method
     * @return json_encode($transactions)
     */

    public function get_transaction_date()
    {
        if ($this->request->is('ajax'))
        {
            //get date
            $date = $this->request->data('value');
            $this->Transaction->recursive = 0;
            $this->paginate = array('conditions' => array('Wallet.user_id' => $this->Auth->user('id'), 'Wallet.default' => '1', 'Transaction.created LIKE' => "$date%"), 'order' => array('Transaction.created' => 'DESC'));
            //$wallets = $this->Transaction->Wallet->find('all', array('conditions' => array('Wallet.user_id' => $this->Auth->user('id')),'Category.name'=>'Cho Vay' , 'recursive' => -1));
            $transactions = $this->Paginator->paginate();
            //debug($wallets);
            //debug(json_encode($transactions)); die;
            echo json_encode($transactions);
        }
        $this->autoRender = false;
    }

    /*
     * get transactions by category
     * @return json_encode($transactions)
     */

    public function get_transaction_cate()
    {
        if ($this->request->is('ajax'))
        {
            //get id category
            $id_cate = $this->request->data('value');
            $this->Transaction->recursive = 0;
            $this->paginate = array('conditions' => array('Wallet.user_id' => $this->Auth->user('id'), 'Wallet.default' => '1', 'Category.id' => $id_cate), 'order' => array('Transaction.created' => 'DESC'));
            //$wallets = $this->Transaction->Wallet->find('all', array('conditions' => array('Wallet.user_id' => $this->Auth->user('id')),'Category.name'=>'Cho Vay' , 'recursive' => -1));
            $transactions = $this->Paginator->paginate();
            //debug($wallets);
            //debug(json_encode($transactions)); die;
            echo json_encode($transactions);
        }
        $this->autoRender = false;
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null)
    {
        if (!$this->Transaction->exists($id))
        {
            throw new NotFoundException(__('Invalid transaction'));
        }
        $options = array('conditions' => array('Transaction.' . $this->Transaction->primaryKey => $id));
        $this->set('transaction', $this->Transaction->find('first', $options));
        //debug($this->Transaction->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        $condition_wallet = array('Wallet.user_id' => $this->Auth->user('id'));
        $wallets = $this->Transaction->Wallet->find('list', array('conditions' => $condition_wallet));
        if ($wallets == null)
        {
            $this->Session->setFlash('You have not wallet! Please add your wallet.', 'alert-danger');
            $this->redirect(array('controller' => 'wallets', 'action' => 'add', $this->Auth->user('id')));
        } else
        {

            //$this->loadModel('Transaction');
            //Get category spent
            $condition_cate = array('Category.type' => '1', array('or' => array(array('Category.user_id' => $this->Auth->user('id')), array('Category.user_id' => 20))));
            $categories = $this->Transaction->Category->find('list', array('conditions' => $condition_cate, 'recursive' => 0));
            $condition_wallet = array('Wallet.user_id' => $this->Auth->user('id'));
            $wallets = $this->Transaction->Wallet->find('list', array('conditions' => $condition_wallet));
            //$parentTransactions = $this->Transaction->ParentTransaction->find('list');
            $this->set(compact('categories', 'wallets', 'parentTransactions'));
        }
        if ($this->request->is('post'))
        {
            $this->Transaction->create();
            $data = $this->request->data;
            //debug($data);
            $money = $data['Transaction']['money'];

            /* Get type Category. type = 0: Spent -> update: current-money = current-money - money
             *  type = 1: Earn from -> update: current-money = current-money + money. 
             *
             */
            //Get type
            $options = array('fields' => 'Category.id, Category.type', 'conditions' => array('Category.id' => $data['Transaction']['category_id']));
            //debug($this->Category->find('first',$options));
            $this->loadModel('Category');
            $category = $this->Category->find('first', $options);
            $type = $category['Category']['type'];

            //Default with_who: someOne
            if ($data['Transaction']['with_who'] == null || $data['Transaction']['with_who'] == '')
            {
                $data['Transaction']['with_who'] = 'someOne';
            }

            if ($this->Transaction->save($data))
            {
                //Get id transaction
                // $id = $this->Transaction->getLastInsertId();
                $idWallet = $data['Transaction']['wallet_id'];
                //debug($id);
                //InsertSuccess Update current-money on tb_wallets.
                if ($type == 0)
                {

                    $sql = "UPDATE tb_wallets SET current_money = current_money - {$money}, spent = spent+{$money} WHERE id = {$idWallet}";
                } else
                {
                    $sql = "UPDATE tb_wallets SET current_money = current_money+{$money}, earn = earn+{$money} WHERE id = {$idWallet}";
                }

                $this->loadModel('Wallet');
                $this->Wallet->query($sql);

                $this->Session->setFlash(__('The transaction has been saved.', 'alert-success'));
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The transaction could not be saved. Please, try again.', 'alert-danger'));
            }
        }
        // debug($categories);
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null)
    {

        if (!$this->Transaction->exists($id))
        {
            throw new NotFoundException(__('Invalid transaction'));
        }
        if ($this->request->is(array('post', 'put')))
        {
            $this->Transaction->id = $id;
            if ($this->Transaction->save($this->request->data))
            {
                $data = $this->request->data;

                //Get type category of transaction
                $type = $data['Transaction']['type'];

                //Get ID wallet update
                $walletId = $data['Transaction']['wallet_id'];

                //Get money update new
                $money = $data['Transaction']['money'];

                //Get information this wallet update
                $walletInfors = $this->Transaction->Wallet->find('all', array('conditions' => array('Wallet.id' => $walletId), 'fields' => array('Wallet.id', 'Wallet.current_money', 'Wallet.spent', 'Wallet.earn'), 'recursive' => 0));
                //Money transaction old
                $moneyTransactions = $this->Session->read('moneyTransaction');
                $moneyTransaction = $moneyTransactions['money'];
                //Wallet infor update
                $walletInfor = $walletInfors[0]['Wallet'];

                //Money current in wallet update
                $current_money = $walletInfor['current_money'];

                //Amount money earned of wallet update
                $earn = $walletInfor['earn'];

                //Amount money spented of wallet update
                $spent = $walletInfor['spent'];

                //Old wallet
                $walletOld_id = $this->Session->read('walletOld_id');

                $isChangeWallet = false;
                if ($walletId != $walletOld_id)
                {
                    $isChangeWallet = true;
                }

                //Check wallet
                /*
                 * if wallet not change --> Updatemoney
                 * if wallet_current != wallet_id
                 * Update wallet old
                 * if(type_category = 1): current_money = current_money + $moneyTransaction, spent = spent - $moneyTransaction
                 * else: current_money = current_money - $moneyTransaction, earn = earn - $moneyTransaction.
                 * 
                 * 
                 */
                if ($isChangeWallet)
                {
                    //Get information if walletOld_id # wallet update
                    $walletOldInfors = $this->Transaction->Wallet->find('all', array('conditions' => array('Wallet.id' => $walletOld_id), 'fields' => array('Wallet.id', 'Wallet.current_money', 'Wallet.spent', 'Wallet.earn'), 'recursive' => 0));
                    //Money current in wallet update
                    $currentOld_money = $walletOldInfors[0]['Wallet']['current_money'];

                    //Amount money earned of wallet update
                    $earnOld = $walletOldInfors[0]['Wallet']['earn'];

                    //Amount money spented of wallet update
                    $spentOld = $walletOldInfors[0]['Wallet']['spent'];
                }


                //Check type: if get type = 1: is spent on
                //  type: 2: earn form
                if ($type == 1)
                {
                    //Update money: moneyTransaction old - money new update.
                    $current_money = $current_money - abs($moneyTransaction - $money);
                    //Spent 
                    $spent = $spent + abs($moneyTransaction - $money);

                    $updateMoney = array('Wallet' => array('id' => $walletId, 'current_money' => $current_money, 'spent' => $spent));

                    if ($isChangeWallet)
                    {
                        $currentOld_money = $currentOld_money + $moneyTransaction;
                        $spentOld = $spentOld - $moneyTransaction;
                        $updateWalletOld = array('Wallet' => array('id' => $walletOld_id, 'current_money' => $currentOld_money, 'spent' => $spentOld));
                    }
                } else
                {
                    $current_money = $current_money + abs($moneyTransaction - $money);
                    //Earn
                    $earn = $earn + abs($moneyTransaction - $money);

                    $updateMoney = array('Wallet' => array('id' => $walletId, 'current_money' => $current_money, 'earn' => $earn));

                    if ($isChangeWallet)
                    {
                        $currentOld_money = $currentOld_money - $moneyTransaction;
                        $earnOld = $earnOld - $moneyTransaction;
                        $updateWalletOld = array('Wallet' => array('id' => $walletOld_id, 'current_money' => $currentOld_money, 'earn' => $earnOld));
                    }
                }
                //Update money
                if ($this->Transaction->Wallet->save($updateMoney))
                {
                    if ($isChangeWallet)
                    {
                        if ($this->Transaction->Wallet->save($updateWalletOld))
                        {
                            $this->Session->setFlash(__('The transaction has been saved.'), 'alert-success');
                            return $this->redirect(array('action' => 'index'));
                        } else
                        {
                            $this->Session->setFlash('This Transaction havent update!', 'alert-danger');
                        }
                    } else
                    {
                        $this->Session->setFlash(__('The transaction has been saved.'), 'alert-success');
                        return $this->redirect(array('action' => 'index'));
                    }
                }
            } else
            {
                $this->Session->setFlash(__('The transaction could not be saved. Please, try again.'));
            }
        } else
        {
            $options = array('conditions' => array('Transaction.' . $this->Transaction->primaryKey => $id));
            $transaction = $this->Transaction->find('first', $options);
            $this->request->data = $transaction;
            // debug($this->Transaction->find('first', $options));
            $this->Session->write('walletOld_id', $transaction['Transaction']['wallet_id']);
        }
        $idTran = $id;
        //get type of category
        $category = $this->Transaction->Category->query("SELECT type ,name , Category.id, money
                                                        FROM tb_categories AS Category, tb_transactions AS tran
                                                        WHERE tran.category_id = Category.id
                                                        AND tran.id ={$idTran}");
        $currentCategory = $category[0]['Category'];
        $money_transaction = $category[0]['tran'];
        //create session current money to compare with money input
        $this->Session->write('moneyTransaction', $money_transaction);
        $categories = $this->Transaction->Category->find('list', array('conditions' => array('OR' => array(array('Category.user_id' => $this->Auth->user('id')), array('Category.user_id' => 20)), 'Category.type' => $currentCategory['type'] + 1), 'fields' => array('Category.id', 'Category.name')));
        $wallets = $this->Transaction->Wallet->find('list', array('conditions' => array('Wallet.user_id' => $this->Auth->user('id'))));
        $this->set(compact('categories', 'wallets', 'currentCategory'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null)
    {
        $this->Transaction->id = $id;
        if (!$this->Transaction->exists())
        {
            throw new NotFoundException(__('Invalid transaction'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Transaction->delete())
        {
            $this->Session->setFlash(__('The transaction has been deleted.'));
        } else
        {
            $this->Session->setFlash(__('The transaction could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

    /**
     * getcategory method
     * @return json_encode($categories) Description: get list category for ajax
     */
    public function getcategory()
    {
        $this->autoRender = false;
        if ($this->request->is('ajax'))
        {
            $value = $this->request->data('value');
            $condition = array('Category.type' => $value, array('or' => array(array('Category.user_id' => $this->Auth->user('id')), array('Category.user_id' => 20))));
            $categories = $this->Transaction->Category->find('list', array('conditions' => $condition));
            //debug($categories);
            echo json_encode($categories);
        }
    }

    /**
     * get listpay method
     * @return $listpay Description
     */
    public function listpay()
    {
        $id = $this->Auth->user('id');
        $sql = "SELECT money, w.id AS wallet_id, w.name, with_who, tran.id AS transaction_id
                FROM `tb_categories` AS cat, tb_wallets AS w, tb_transactions AS tran
                WHERE w.user_id = {$id}
                AND w.id = tran.wallet_id
                AND tran.category_id = cat.id
                AND tran.parent_id = 0
                AND cat.id =3

                ";
        $pays = $this->Transaction->query($sql);
        $this->set(compact('pays'));
    }

    /**
     * get list revenue method
     * @return $listreneue Description
     */
    public function listrevenue()
    {
        $id = $this->Auth->user('id');
        $sql = "SELECT money, w.id AS wallet_id, w.name, with_who, tran.id AS transaction_id
                FROM `tb_categories` AS cat, tb_wallets AS w, tb_transactions AS tran
                WHERE w.user_id = {$id}
                AND w.id = tran.wallet_id
                AND tran.category_id = cat.id
                AND cat.id =8
                AND tran.parent_id = 0

                ";
        $revenues = $this->Transaction->query($sql);
        $this->set(compact('revenues'));
        //debug($this->Transaction->query($sql));die();
    }

    /*
     * pay method
     * @param int $id
     * @return void
     */

    public function pay($id = null)
    {
        $sql = $this->Transaction->find('first', array('conditions' => array('Transaction.id' => $id)));

        if ($this->request->is(array('post', 'put')))
        {
            if (!$this->Transaction->exists($id))
            {
                $this->Session->setFlash('This Transaction not existed!', 'alert-danger');
                $this->redirect(array('action' => 'listrevenue'));
            } else
            {
                $data_money = $this->request->data;
                //$data['Transaction']['id'] = $id+1;
                $money = $data_money['Transaction']['money'];
                // $data['Transaction'] = $sql['Transaction'];
                $data['Transaction']['category_id'] = $sql['Transaction']['category_id'];
                $data['Transaction']['wallet_id'] = $sql['Transaction']['wallet_id'];
                $data['Transaction']['parent_id'] = $id;
                $data['Transaction']['money'] = $money;
                $data['Transaction']['with_who'] = $sql['Transaction']['with_who'];

                //Check money revenue.
                /**
                 * if(money revenue > money borrow) -> show error
                 * else -> insert transaction
                 * 
                 */
                $transaction = $this->Session->read('transaction');

                //get sum money revenued
                $re_money = 0;
                foreach ($transaction['ChildTransaction'] as $child)
                {
                    $re_money = $re_money + $child['money'];
                }
                if ($money > ($sql['Transaction']['money'] - $re_money))
                {
                    $this->Session->setFlash('Money Pay Biger Than Old Money!!', 'alert-danger');
                    $this->redirect(array('action' => 'revenue', $id));
                } else
                {
                    //Update Money In Wallet
                    //Update Transaction Parent
                    $wallet_id = $sql['Wallet']['id'];
                    $current_money = $sql['Wallet']['current_money'];
                    $earn = $sql['Wallet']['earn'];

                    $current_money = $current_money - $money;
                    $earn = $earn - $money;


                    if ($this->Transaction->save($data) and $this->Transaction->Wallet->save(array('id' => $wallet_id, 'current_money' => $current_money, 'earn' => $earn)))
                    {
                        $this->Session->setFlash('Pay SuccessFull!!', 'alert-success');
                        $this->redirect(array('action' => 'index'));
                    } else
                    {
                        $this->Session->setFlash('Pay Error!!', 'alert-danger');
                        $this->redirect(array('action' => 'index'));
                    }
                }


                //debug($data);
            }
        } else
        {
            $transaction = $this->Transaction->find('first', array('conditions' => array('Transaction.id' => $id)));
            $this->request->data = $transaction;
            $this->Session->write('transaction', $transaction);
            $this->set(compact('transaction'));
        }
    }

    public function revenue($id = null)
    {
        $sql = $this->Transaction->find('first', array('conditions' => array('Transaction.id' => $id)));
        // debug($sql); die;

        if ($this->request->is(array('post', 'put')))
        {
            if (!$this->Transaction->exists($id))
            {
                $this->Session->setFlash('This Transaction not existed!', 'alert-danger');
                $this->redirect(array('action' => 'listrevenue'));
            } else
            {
                $data_money = $this->request->data;
                //$data['Transaction']['id'] = $id+1;
                $money = $data_money['Transaction']['money'];
                // $data['Transaction'] = $sql['Transaction'];
                $data['Transaction']['category_id'] = $sql['Transaction']['category_id'];
                $data['Transaction']['wallet_id'] = $sql['Transaction']['wallet_id'];
                $data['Transaction']['parent_id'] = $id;
                $data['Transaction']['money'] = $money;
                $data['Transaction']['with_who'] = $sql['Transaction']['with_who'];
                // $date = new date("Y-m-d H:i:s");
                //$data['Transaction']['created'] = NOW();
                //Check money revenue.
                $transaction = $this->Session->read('transaction');
                $re_money = 0;
                foreach ($transaction['ChildTransaction'] as $child)
                {
                    $re_money = $re_money + $child['money'];
                }
//                debug($money);
//                debug( $sql['Transaction']['money'] - $re_money);
//                die;
                if ((int) $money > ($sql['Transaction']['money'] - $re_money))
                {
                    $this->Session->setFlash('Money Revenued Biger Than Old Money!!', 'alert-danger');
                    $this->redirect(array('action' => 'revenue', $id));
                } else
                {
                    //Update Money In Wallet
                    //Update Transaction Parent
                    $wallet_id = $sql['Wallet']['id'];
                    $current_money = $sql['Wallet']['current_money'];
                    $spent = $sql['Wallet']['spent'];

                    $current_money = $current_money + $money;
                    $spent = $spent - $money;

                    // debug($this->Transaction->save($data));die;
                    if ($this->Transaction->save($data) and $this->Transaction->Wallet->save(array('id' => $wallet_id, 'current_money' => $current_money, 'spent' => $spent)))
                    {
                        $this->Session->setFlash('Revenued SuccessFull!!', 'alert-success');
                        $this->redirect(array('action' => 'index'));
                    } else
                    {
                        $this->Session->setFlash('Revenued SuccessFull!!', 'alert-success');
                        $this->redirect(array('action' => 'index'));
                    }
                }


                //debug($data);
            }
        } else
        {
            $transaction = $this->Transaction->find('first', array('conditions' => array('Transaction.id' => $id)));
            //$this->request->data = $transaction;
            $this->Session->write('transaction', $transaction);
            $this->set(compact('transaction'));
        }
    }

    /*
     * list date method
     * @return lisdate
     */

    public function viewdate()
    {
        $sql = "SELECT DISTINCT left(created,10) AS date FROM tb_transactions ORDER BY id DESC";
        $date = $this->Transaction->query($sql);
        $group = array();
        //$group[0] = date('Y-m-d');
        foreach ($date as $key => $value)
        {
            $group[$key] = $value[0]['date'];
        }
        return $group;
        $this->autoRender = false;
    }

    /*
     * get list categories spent method
     * @return list categories
     */

    public function getcatefirst()
    {

        $userId = $this->Auth->user('id');
        $sql = "SELECT cat.id, name
                    FROM tb_categories AS cat
                    WHERE type = 1
                    AND cat.user_id = 20
                    OR cat.user_id = {$userId}
                    ";
        $this->loadModel('Category');
        $datas = $this->Category->query($sql);
        foreach ($datas as $item)
        {
            $categories[$item['cat']['id']] = $item['cat']['name'];
        }

        return $categories;
        $this->autoRender = false;
    }

    /*
     * get list categories for ajax
     * @return json_encode($categories)
     */

    public function getcategories()
    {
        $this->autoRender = false;
        if ($this->request->is('ajax'))
        {
            $type = $this->request->data('value');
            //value = 1: Sept; 2:Earn
            $userId = $this->Auth->user('id');
            $sql = "SELECT cat.id, name
                    FROM tb_categories AS cat
                    WHERE type = {$type}
                    AND cat.user_id = 20
                    OR cat.user_id = {$userId}
                    ";
            $this->loadModel('User');
            $datas = $this->Category->query($sql);
            $categories = array();
            $parent['0'] = '-- No Parent --';
            foreach ($datas as $item)
            {
                $categories[$item['cat']['id']] = $item['cat']['name'];
            }
            echo(json_encode($categories));
        }
    }

}
